<?php
/**
 * BootAdmin is committed to providing solutions for quickly building web applications
 * Please view the LICENSE file that was distributed with this source code,
 * For the full copyright and license information.
 * Thank you very much for using BootAdmin.
 *
 * @Author G.r<root@BootAdmin.com>
 */

declare (strict_types=1);

namespace app\admin\logic;

use app\common\logic\BaseLogic;
use app\common\model\Config;
use think\db\exception\DbException;
use think\Exception;
use think\facade\Cache;

/**
 * 配置逻辑
 */
class ConfigLogic extends BaseLogic
{
    protected Config $model;

    /**
     * 初始化
     */
    public function __construct()
    {
        $this->model = new Config();
    }

    /**
     * 获取列表
     */
    public function list($params, bool $onlyTrashed = false)
    {
        $configGroup = get_sys_config('config_group');
        $config = $this->model->setParams($params)->queryBuilder()->select()->toArray();
        $list        = [];
        $newConfigGroup = [];
        foreach ($config as $item) {
            $list[$item['group']]['list'][] = $item;
        }
        foreach ($configGroup as $item) {
            $list[$item['key']]['name']  = $item['key'];
            $list[$item['key']]['title'] = $item['value'];

            $newConfigGroup[$item['key']] = $list[$item['key']]['title'];
        }
        return $newConfigGroup;
    }

    /**
     * 新增数据
     * @param $params
     * @return bool
     */
    public function add($params)
    {
        $result = $this->model->setParams($params)->add();
        if (!$result) {
            $this->throw($this->model->getError());
        }
        Cache::tag(Config::$cacheTag)->clear();
        return $result;
    }

    /**
     * 修改数据
     * @param $params
     * @return bool
     */
    public function edit($params)
    {
        try {
            $all = $this->model->select();
            $configValue = [];
            foreach ($all as $item) {
                if (array_key_exists($item->name, $params)) {
                    $configValue[] = [
                        'id'    => $item->id,
                        'type'  => $item->getData('type'),
                        'value' => $params[$item->name]
                    ];
                }
            }
        } catch (DbException $e) {
            $this->throw($e->getMessage());
        }

        $result = false;
        $this->model->startTrans();
        try {
            $result = $this->model->saveAll($configValue);
            Cache::tag(Config::$cacheTag)->clear();
            $this->model->commit();
        } catch (Exception $e) {
            $this->model->rollback();
            $this->throw($e->getMessage());
        }
        return $result;
    }
}